const fs = require('fs-extra');
const path = require('path');
const logger = require('../utils/logger');
const readline = require('readline');

class FirstRunSetup {
  constructor() {
    this.rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });
  }

  async showSetupPrompt() {
    console.log('\n🎉 欢迎使用 NapCat Webhook 接收端');
    console.log('=====================================\n');
    
    console.log('检测到您是首次运行，需要进行基本配置：\n');
    
    try {
      // 获取用户配置
      const userConfig = await this.getUserConfig();
      
      // 更新配置
      await this.saveConfig(userConfig);
      
      // 创建必要的目录
      await this.createDirectories();
      
      console.log('\n✅ 配置完成！正在启动服务...\n');
      
      // 重启应用
      setTimeout(() => {
        console.log('请重新运行: npm start');
        process.exit(0);
      }, 2000);
      
    } catch (error) {
      logger.error('首次运行配置失败:', error);
      console.log('\n❌ 配置失败，请检查错误信息后重试\n');
      process.exit(1);
    } finally {
      this.rl.close();
    }
  }

  question(prompt) {
    return new Promise((resolve) => {
      this.rl.question(prompt, resolve);
    });
  }

  async getUserConfig() {
    const config = {};
    
    // NapCat 服务器配置
    console.log('📡 NapCat 服务器配置:');
    config.napcatUrl = await this.question(`NapCat 服务器地址 [默认: http://192.168.5.4:3000]: `) || 'http://192.168.5.4:3000';
    config.token = await this.question('NapCat Token [留空如果无需验证]: ');
    
    // Webhook 配置
    console.log('\n🔗 Webhook 配置:');
    config.webhookSecret = await this.question('Webhook 密钥 [留空如果无需验证]: ');
    
    // 服务器配置
    console.log('\n🚀 服务器配置:');
    const port = await this.question('Webhook 端口 [默认: 8080]: ');
    config.port = port || '8080';
    
    return config;
  }

  async saveConfig(userConfig) {
    const configPath = path.join(__dirname, '../../config/development.json');
    
    // 构建新配置
    const newConfig = {
      server: {
        port: parseInt(userConfig.port) || 8080,
        host: "0.0.0.0"
      },
      napcat: {
        baseUrl: userConfig.napcatUrl,
        token: userConfig.token,
        timeout: 30000
      },
      webhook: {
        path: "/webhook",
        secret: userConfig.webhookSecret,
        enableSignature: !!userConfig.webhookSecret
      },
      storage: {
        basePath: "./data",
        images: "images",
        voices: "voices",
        videos: "videos", 
        files: "files",
        texts: "texts"
      },
      firstRun: false
    };
    
    await fs.writeJson(configPath, newConfig, { spaces: 2 });
    console.log('✅ 配置文件已更新:', configPath);
  }

  async createDirectories() {
    const dirs = [
      './data/images',
      './data/voices', 
      './data/videos',
      './data/files',
      './data/texts',
      './logs'
    ];
    
    for (const dir of dirs) {
      await fs.ensureDir(dir);
      console.log(`✅ 创建目录: ${dir}`);
    }
  }
}

module.exports = new FirstRunSetup();